﻿package utils
{
	import flash.events.*;
	import flash.net.*;
	import flash.xml.*;
	
	
	public class XMLimport extends EventDispatcher 
	{
		private var _data:Array;
		private var loader:URLLoader;
		private var FileType:String;
		
		private var status:Number;
		public var xml:XML=new XML;
		
		public function XMLimport()
		{
			loader = new URLLoader;
			loader.addEventListener(Event.COMPLETE,onLoadedXML);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,errorHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,statusHandler);
		}
		
		public function load(file:String,_type:String,xml:XML,embedded:Boolean=false):void 
		{
			
			FileType = _type;
			
			if (embedded)
			{
				parseData(xml);
			}
			else
			{
				try 
				{
				loader.load(new URLRequest(file));
				} 
				catch (e:Error) 
				{
					trace('cant connect :s because' + e.message);
				}
			}
		}
		
		private function parseData(xml:XML):void
		{
			switch(FileType)
			{
				case 'button':
				_data = MediaRSS.parse(xml);
				break;
				
				case 'preset':
				_data = MediaRSS.parsePreset(xml);
				break;
			}
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function onLoadedXML(e:Event):void 
		{
			try 
			{
				var dat:XML=XML(e.target.data);
			} 
			catch (err:Error) 
			{
				
				dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,':s'));
				return;
			}
			
			switch(FileType)
			{
				case 'button':
				_data = MediaRSS.parse(dat);
				break;
				
				case 'preset':
				_data = MediaRSS.parsePreset(dat);
				break;
			}
			
			dispatchEvent(new Event(Event.COMPLETE));
		}

		private function statusHandler(evt:HTTPStatusEvent):void
		{
			status=evt.status;
		}
		
		/** Catch security and io errors **/
		private function errorHandler(evt:ErrorEvent):void
		{
			dispatchEvent(new ErrorEvent(ErrorEvent.ERROR,false,false,status + ': ' + evt.text));
		}

		public function get data():Array 
		{
			return _data;
		}
	}
}